package com.ic.util;

import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;
import java.util.logging.Logger;

/**
 * Description: 本类继承spring的PropertyPlaceholderConfigurer类
 * 并重新定义processProperties方法，对数据库配置内容进行解密
 * <p>
 * Author: zen_hu
 * Date  : 2017/1/10
 * Time  : 8:29
 */
public class EncryptablePropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

	public static final Logger LOGGER = Logger.getLogger(EncryptablePropertyPlaceholderConfigurer.class.toString());
	// 数据库驱动
	public static final String JDBC_DRIVER_CLASSNAME = "hcp.jdbc.driverClassName";
	// 数据库访问URL
	public static final String JDBC_URL = "hcp.jdbc.url";
	// 数据库访问用户名
	public static final String JDBC_USERNAME = "hcp.jdbc.username";
	// 数据库访问密码
	public static final String JDBC_PASSWORD = "hcp.jdbc.password";

	/**
	 * 获取.properties配置文件信息，并采用Base64对信息内容进行解密
	 * 相关内容请查看{@link CryptographyUtil#decBase64}
	 *
	 * @param beanFactory ConfigurableListableBeanFactory实例
	 * @param props       属性配置类
	 */
	protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeanInitializationException {

		String driverClassName = props.getProperty(JDBC_DRIVER_CLASSNAME);
		String url = props.getProperty(JDBC_URL);
		String username = props.getProperty(JDBC_USERNAME);
		String password = props.getProperty(JDBC_PASSWORD);

		if (!StringUtil.notNullAndNotBlank(driverClassName, url, username, password)) {
			throw new BeanInitializationException("数据库配置属性jdbc.properties文件内容配置错误！");
		}

		props.setProperty(JDBC_DRIVER_CLASSNAME, CryptographyUtil.decBase64(driverClassName));
		props.setProperty(JDBC_URL, CryptographyUtil.decBase64(url));
		props.setProperty(JDBC_USERNAME, CryptographyUtil.decBase64(username));
		props.setProperty(JDBC_PASSWORD, CryptographyUtil.decBase64(password));
		super.processProperties(beanFactory, props);
	}
}